package com.xjj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjj.entity.Parent;
import com.xjj.entity.ResponseEntity;
import com.xjj.entity.Student;
import com.xjj.mapper.ParentMapper;
import com.xjj.service.ParentService;
import com.xjj.service.StudentService;
import com.xjj.util.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sxy
 * @version 1.0
 * @date 2022/10/20 17:02
 */
@Service
@Slf4j
public class ParentServiceImpl extends ServiceImpl<ParentMapper, Parent> implements ParentService {


    @Resource
    StudentService studentService;

    @Transactional
    @Override
    public Parent login(String tel) {
        // 1、先根据手机号查询家长信息
        Parent parent = query().eq("tel", tel).one();
        List<Student> students = studentService.getByTel(tel);

        // 2、如果不存在家长信息
        if (parent == null) {
            // 并且不存在学生信息
            if (students == null || students.isEmpty()) {
                throw new BusinessException("无家长信息");
            }
            // 存在学生信息，说明家长首次登录
            parent = new Parent();
            parent.setTel(tel);
            parent.setName(students.get(0).getName() + "家长");

            // 将家长存进数据库
            save(parent);

            // 更新每个学生的家长 id
            Integer parentId = parent.getId();
            System.out.println(">>>>>>>>>>> parent : " + parent);

            List<Integer> studentIds = students.stream().map(Student::getId).collect(Collectors.toList());

            // 更新数据库
            studentService.update().setSql("parent_id = " + parentId).in("id", studentIds).update();

            // 更新集合
            for (Student student : students) {
                student.setParentId(parentId);
            }
        }
        // 将学生集合赋值给家长
        parent.setChildren(students);


        // 返回数据
        return parent;
    }
}
